# banner.py
from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
from pathlib import Path
from PIL import Image
from io import BytesIO

router = APIRouter()

IMAGE_DIR = Path(__file__).parent.parent / "assets" / "banner"

MAX_DIMENSION = 1024  # 最大边不能超过512像素

def process_image(buffer: BytesIO) -> BytesIO:
    with Image.open(buffer) as img:
        # 缩放图片
        width, height = img.size
        scale = min(MAX_DIMENSION / max(width, height), 1.0)
        new_size = (int(width * scale), int(height * scale))
        resized_img = img.resize(new_size, Image.LANCZOS)

        # 保存压缩后的图片到新的 buffer
        out_buffer = BytesIO()
        save_kwargs = {}
        if img.format == "JPEG":
            save_kwargs["quality"] = 80
        resized_img.save(out_buffer, format=img.format, **save_kwargs)
        out_buffer.seek(0)
        return out_buffer

@router.get("/file/{filename}")
async def get_image_file(filename: str):
    safe_filename = Path(filename).name
    file_path = IMAGE_DIR / safe_filename

    if not file_path.exists():
        raise HTTPException(status_code=404, detail="图片文件未找到")

    try:
        with open(file_path, "rb") as f:
            buffer = BytesIO(f.read())

        processed = process_image(buffer)
        img_format = Image.open(processed).format.lower()
        processed.seek(0)

        return StreamingResponse(processed, media_type=f"image/{img_format}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"图片处理失败: {str(e)}")

@router.get("/file_rotate/{filename}")
async def get_rotated_image_file(filename: str):
    safe_filename = Path(filename).name
    file_path = IMAGE_DIR / safe_filename

    if not file_path.exists():
        raise HTTPException(status_code=404, detail="图片文件未找到")

    try:
        with Image.open(file_path) as img:
            rotated = img.rotate(-90, expand=True)
            buffer = BytesIO()
            rotated.save(buffer, format=img.format)
            buffer.seek(0)

        processed = process_image(buffer)
        img_format = Image.open(processed).format.lower()
        processed.seek(0)

        return StreamingResponse(processed, media_type=f"image/{img_format}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"图片处理失败: {str(e)}")


@router.get("/list", response_class=JSONResponse)
async def list_image_files():
    image_extensions = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}
    image_files = [f.name for f in IMAGE_DIR.iterdir() if f.suffix.lower() in image_extensions]

    if not image_files:
        raise HTTPException(status_code=404, detail="没有找到任何图片文件")
    
    return {
        "count": len(image_files),
        "data": image_files
    }
